import { Request, Response } from 'express';
import { AuthRequest } from '@/types';
import deptService from '@/services/system/dept.service';
import ApiResponse from '@/utils/api/api-response.util';
import { Log, BusinessType } from '@/decorators/Log';
import { RepeatSubmit } from '@/decorators/repeatSubmit.decorator';
import { getLogger } from '@/utils/logger';

// 创建模块专用的日志记录器
const consoleLogger = getLogger("dept-controller");
const logger = getLogger("dept-controller", {
  console: false,
});

/**
 * 部门信息控制器
 */
class DeptController {
  /**
   * 获取部门列表
   * @param req 请求对象
   * @param res 响应对象
   */
  async list(req: AuthRequest, res: Response) {
    try {
      // 请求日志
      consoleLogger.info("获取部门列表请求", {
        query: req.query,
        operator: req.user?.userName || 'unknown',
      });
      
      // 获取查询参数
      const params = req.query;
      
      // 如果有数据权限条件，则添加到查询参数中
      if (req.dataScope) {
        params.dataScope = req.dataScope;
      }
      
      // 查询部门列表
      const data = await deptService.selectDeptList(params);
      
      // 结果日志
      logger.info("获取部门列表成功", {
        response: {
          count: data.length
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, data);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`获取部门列表失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          query: req.query,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '获取部门列表失败');
      }
    }
  }
  
  /**
   * 查询部门列表(排除节点)
   * @param req 请求对象
   * @param res 响应对象
   */
  async listExcludeChild(req: AuthRequest, res: Response) {
    try {
      const deptId = parseInt(req.params.deptId);
      
      // 请求日志
      consoleLogger.info("获取部门列表(排除节点)请求", {
        params: req.params,
        query: req.query,
        operator: req.user?.userName || 'unknown',
      });
      
      // 获取查询参数
      const params = req.query;
      
      // 如果有数据权限条件，则添加到查询参数中
      if (req.dataScope) {
        params.dataScope = req.dataScope;
      }
      
      // 查询部门列表
      const depts = await deptService.selectDeptList(params);
      
      // 过滤掉指定部门及其子部门
      const childIds = await deptService.selectChildrenDeptById(deptId);
      const childIdSet = new Set(childIds.map(dept => dept.deptId).concat([deptId]));
      
      const filteredDepts = depts.filter(dept => !childIdSet.has(dept.deptId));
      
      // 结果日志
      logger.info("获取部门列表(排除节点)成功", {
        response: {
          deptId,
          totalCount: depts.length,
          filteredCount: filteredDepts.length
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, filteredDepts);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`获取部门列表(排除节点)失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          params: req.params,
          query: req.query,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '获取部门列表失败');
      }
    }
  }
  
  /**
   * 获取部门树列表
   * @param req 请求对象
   * @param res 响应对象
   */
  async treeSelect(req: AuthRequest, res: Response) {
    try {
      // 请求日志
      consoleLogger.info("获取部门树列表请求", {
        query: req.query,
        operator: req.user?.userName || 'unknown',
      });
      
      // 获取查询参数
      const params = req.query;
      
      // 如果有数据权限条件，则添加到查询参数中
      if (req.dataScope) {
        params.dataScope = req.dataScope;
      }
      
      // 查询部门树结构
      const data = await deptService.selectDeptTreeList(params);
      
      // 结果日志
      logger.info("获取部门树列表成功", {
        response: {
          count: Array.isArray(data) ? data.length : 0
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, data);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`获取部门树列表失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          query: req.query,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '获取部门树列表失败');
      }
    }
  }
  
  /**
   * 根据角色ID查询部门树信息
   * @param req 请求对象
   * @param res 响应对象
   */
  async roleDeptTreeSelect(req: AuthRequest, res: Response) {
    try {
      const roleId = parseInt(req.params.roleId);
      
      // 请求日志
      consoleLogger.info("根据角色ID查询部门树信息请求", {
        params: req.params,
        query: req.query,
        operator: req.user?.userName || 'unknown',
      });
      
      // 获取查询参数
      const params = req.query;
      
      // 如果有数据权限条件，则添加到查询参数中
      if (req.dataScope) {
        params.dataScope = req.dataScope;
      }
      
      // 查询部门树结构
      const depts = await deptService.selectDeptTreeList(params);
      
      // 查询角色部门
      const checkedKeys = await deptService.selectDeptListByRoleId(roleId, req.query.deptCheckStrictly === 'true');
      
      // 结果日志
      logger.info("根据角色ID查询部门树信息成功", {
        response: {
          roleId,
          deptsCount: Array.isArray(depts) ? depts.length : 0,
          checkedKeysCount: Array.isArray(checkedKeys) ? checkedKeys.length : 0
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, {
        depts,
        checkedKeys
      });
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`根据角色ID查询部门树信息失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          params: req.params,
          query: req.query,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '查询部门树失败');
      }
    }
  }
  
  /**
   * 获取部门详细信息
   * @param req 请求对象
   * @param res 响应对象
   */
  async getInfo(req: AuthRequest, res: Response) {
    try {
      const deptId = parseInt(req.params.deptId);
      
      // 请求日志
      consoleLogger.info("获取部门详细信息请求", {
        params: req.params,
        operator: req.user?.userName || 'unknown',
      });
      
      // 校验数据权限
      await deptService.checkDeptDataScope(deptId, req.user?.userId!);
      
      // 查询部门信息
      const data = await deptService.selectDeptById(deptId);
      if (!data) {
        consoleLogger.warn("获取部门详细信息 - 部门不存在", {
          deptId,
          operator: req.user?.userName || 'unknown',
        });
        ApiResponse.error(res, '部门不存在');
        return;
      }
      
      // 结果日志
      logger.info("获取部门详细信息成功", {
        response: {
          deptId,
          deptName: data.deptName
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, data);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`获取部门详细信息失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          params: req.params,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '获取部门详细信息失败');
      }
    }
  }
  
  /**
   * 新增部门
   */
  @RepeatSubmit({ expireSeconds: 5 })
  @Log({ title: '部门管理', businessType: BusinessType.INSERT })
  async add(req: AuthRequest, res: Response) {
    try {
      const dept = req.body;
      
      // 请求日志
      consoleLogger.info("新增部门请求", {
        body: req.body,
        operator: req.user?.userName || 'unknown',
      });
      
      // 设置创建者
      dept.createBy = req.user?.userName;
      
      // 新增部门
      const result = await deptService.insertDept(dept);
      
      // 结果日志
      logger.info("新增部门成功", {
        response: {
          deptId: result.deptId,
          deptName: result.deptName
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, result);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`新增部门失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          body: req.body,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '新增部门失败');
      }
    }
  }
  
  /**
   * 修改部门
   */
  @RepeatSubmit({ expireSeconds: 5 })
  @Log({ title: '部门管理', businessType: BusinessType.UPDATE })
  async update(req: AuthRequest, res: Response) {
    try {
      const dept = req.body;
      
      // 请求日志
      consoleLogger.info("修改部门请求", {
        body: req.body,
        operator: req.user?.userName || 'unknown',
      });
      
      // 校验数据权限
      await deptService.checkDeptDataScope(dept.deptId, req.user?.userId!);
      
      // 设置更新者
      dept.updateBy = req.user?.userName;
      
      // 修改部门
      const result = await deptService.updateDept(dept);
      
      // 结果日志
      logger.info("修改部门成功", {
        response: {
          deptId: dept.deptId,
          deptName: dept.deptName
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, result);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`修改部门失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          body: req.body,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '修改部门失败');
      }
    }
  }
  
  /**
   * 删除部门
   */
  @RepeatSubmit({ expireSeconds: 5 })
  @Log({ title: '部门管理', businessType: BusinessType.DELETE })
  async remove(req: AuthRequest, res: Response) {
    try {
      const deptId = parseInt(req.params.deptId);
      
      // 请求日志
      consoleLogger.info("删除部门请求", {
        params: req.params,
        operator: req.user?.userName || 'unknown',
      });
      
      // 校验数据权限
      await deptService.checkDeptDataScope(deptId, req.user?.userId!);
      
      // 删除部门
      const result = await deptService.deleteDeptById(deptId);
      
      // 结果日志
      logger.info("删除部门成功", {
        response: {
          deptId,
          result
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, result);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`删除部门失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          params: req.params,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '删除部门失败');
      }
    }
  }
}

export default new DeptController(); 